﻿using System;
using System.Collections.Generic;
using System.Configuration.Assemblies;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;


namespace Assembly
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        private AppDomain _pluginDomain;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void LoadAndInvokePluginFunction_Click(object sender, RoutedEventArgs e)
        {
            UnloadCurrentPlugin(sender, e);

            // 确保插件目录存在
            var pluginPath = "D:\\Code\\FirstCode\\FirstCode\\Normal\\Assembly\\Assembly\\bin\\Debug";

            Directory.CreateDirectory(pluginPath);

            // 创建新的 AppDomain 并加载插件
            AppDomainSetup domainSetup = new AppDomainSetup
            {
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory
            };
            _pluginDomain = AppDomain.CreateDomain("PluginDomain", null, domainSetup);

            try
            {
                // 创建 PluginLoader 的实例，并调用其方法
                PluginLoader loader = (PluginLoader)_pluginDomain.CreateInstanceAndUnwrap(
                    System.Reflection.Assembly.GetExecutingAssembly().FullName,
                    typeof(PluginLoader).FullName);

                string dllPath = Path.Combine(pluginPath, "ClassLibrary1.dll");
                loader.LoadAndExecutePlugin(dllPath);

                
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载或调用插件时出错: {ex.Message}");
            }
        }

        private void UnloadCurrentPlugin(object sender, RoutedEventArgs e)
        {
            if (_pluginDomain != null)
            {
                // 卸载 AppDomain
                AppDomain.Unload(_pluginDomain);
                _pluginDomain = null;

                // 强制垃圾回收
                GC.Collect();
                GC.WaitForPendingFinalizers();

                // 延迟一段时间再尝试删除文件
                Task.Delay(2000).Wait(); // 等待2秒

                // 尝试删除 DLL 文件
                string dllPath = Path.Combine("D:\\Code\\FirstCode\\FirstCode\\Normal\\Assembly\\Assembly\\bin\\Debug", "ClassLibrary1.dll");

                DeleteFileSafely(dllPath);
            }
        }

        private void DeleteFileSafely(string filePath)
        {
            if (File.Exists(filePath))
            {
                try
                {
                    File.SetAttributes(filePath, FileAttributes.Normal);
                    File.Delete(filePath);
                    MessageBox.Show("旧插件已成功卸载并删除！");
                }
                catch (IOException ex)
                {
                    MessageBox.Show($"无法删除文件: {ex.Message}\n请确保文件未被其他进程占用。");
                }
                catch (UnauthorizedAccessException ex)
                {
                    MessageBox.Show($"访问被拒绝: {ex.Message}\n请确保应用程序有足够的权限。");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
            else
            {
                MessageBox.Show("旧插件文件不存在。");
            }
        }

        private void ServerClick(object sender, RoutedEventArgs e)
        {
            PipeServer.Start(); 
        }
    }
}
        
    
